﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Currency.TextUtils;

using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.WebUtils;
using Newtonsoft.Json;
using RabbitDownload.Helper.Currency;

using System;
using System.Collections.Generic;

namespace RabbitDownload.WebSite.Bcy.Tag
{
    internal class ScannerBcyTag
    {
        /// <summary>
        /// API变更为Get请求，since不变，模式分为tag_id和wid 请自行适配
        /// </summary>
        private string ListApi = "https://bcy.net/circle/timeline/loadtag?since={0}&{1}={2}&sort=hot";

        public void Start(String Tag)
        {
            if (!MessageHelper.AlertNull(Tag))
                return;
            List<string> ArticleList = new List<string>();
            List<string> TaskList = new List<string>();
            String SearchUrl = string.Format("https://bcy.net/search/home?k={0}", WebHelper.UrlEncode(Tag));

            String Shtml = WebHelper.HttpPcGet(SearchUrl);

            foreach (string Url in HtmlHelper.GetLinkVlaueList(Shtml, "//h1[@class='fz16 cut']/a"))
            {
                FloderHelper.OpenFloder("https://bcy.net" + Url);
                if (MessageHelper.DialogResultAlert("这是正确的标签分类吗？"))
                    TaskList.Add("https://bcy.net" + Url);
            }

            foreach (string SingleTask in TaskList)
            {
                Console.WriteLine("启动：" + SingleTask);
                ArticleList.AddRange(ArticleAnalysis(SingleTask));
            }

            Console.WriteLine("扫描完毕！");
        }

        /// <summary>
        /// 分析文章并且分配下载任务
        /// </summary>
        /// <param name="Url"></param>
        public List<string> ArticleAnalysis(string Url)
        {
            Console.WriteLine("顺次解析" + Url);
            String Shtml = WebHelper.HttpPcGet(Url);
            String TagId = GetTagId(Shtml);
            Console.WriteLine("获取到tagid：" + TagId);
            List<string> ArticleList = new List<string>();

            if (TagId != "")
            {
                if (Url.IndexOf("bcy.net/circle/index") > 0)
                {
                    //  发送请求获取json 解析  https://bcy.net/circle/index/5035 这个类型的链接
                    ArticleList.AddRange(SendPost("0", TagId, "wid"));
                }
                else
                {
                    ArticleList.AddRange(SendPost("0", TagId, "tag_id"));
                }
            }
            else
                Console.WriteLine("未能解析到TAGID");
            Bcy.BcyAnalysisContent.AutoDownlod(ArticleList);
            return ArticleList;
        }

        /// <summary>
        /// 获取这个Tag的ID
        /// </summary>
        /// <param name="shtml"></param>
        /// <returns></returns>
        private string GetTagId(string shtml)
        {
            String TagId = "";

            TagId = HtmlHelper.GetFirstAttributes(shtml, "data-wid", "//a[@class='_btn _btn--green _btn--unfollow-xl mt15']");
            if (TagId == "")
            {
                TagId = HtmlHelper.GetFirstAttributes(shtml, "data-tagid", "//a[@class='_btn _btn--green _btn--unfollow-xl mt15']");
            }
            return TagId;
        }

        /// <summary>
        /// 发送请求，获取链接结果
        /// </summary>
        /// <param name="Since"></param>
        /// <param name="TagId"></param>
        /// <param name="Mode">模式分为：模式分为tag_id和wid 请自行适配</param>
        /// <returns></returns>
        private List<string> SendPost(string Since, string TagId, string Mode)
        {
            List<String> ArticleList = new List<string>();

            Console.WriteLine("发送请求:{0}", Since);

            string API = string.Format(new ScannerBcyTag().ListApi, Since, Mode, TagId);
            string Shtml = WebHelper.HttpPcGet(API);
            string SinceTemp = "";
            try
            {
                BcyTagJson.Root AllJson = JsonConvert.DeserializeObject<BcyTagJson.Root>(Shtml);

                foreach (BcyTagJson.DataItem Single in AllJson.data)
                {
                    SinceTemp = Single.since;
                    ArticleList.Add("https://bcy.net/item/detail/" + Single.item_detail.item_id);
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }

            if (SinceTemp != "" && SinceTemp != "0")
                ArticleList.AddRange(SendPost(SinceTemp, TagId, Mode));

            Console.WriteLine("全部扫描完成，待下载：" + ArticleList.Count);
            return ArticleList;
        }
    }
}